package repositories

import (
	"new_ginblog/internal/db"
	"new_ginblog/internal/models"
	"new_ginblog/internal/utils/errormsg"
)

// CheckCategory 检查分类是否存在
func CheckCategory(name string) int {
	var category models.Category
	db.DB.Model(&models.Category{}).Where("name = ?", name).First(&category)
	if category.ID > 0 {
		return errormsg.ERROR_CATEGORY_NAME_USED
	}
	return errormsg.ERROR_CATEGORY_NAME_OK
}

// AddCategory 增加新的分类
func AddCategory(category *models.Category) int {
	err := db.DB.Create(&category).Error
	if err != nil {
		return errormsg.ERROR
	}
	return errormsg.SUCCESS
}

// GetCategoryList 获取分类列表
func GetCategoryList(pageSize int, pageNum int) ([]models.Category, int, int64) {
	var category []models.Category
	var count int64
	err := db.DB.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&category).Count(&count).Error
	if err != nil {
		return nil, errormsg.ERROR, 0
	}
	return category, errormsg.SUCCESS, count
}

// UpdateCategory 修改已有分类
func UpdateCategory(id int, category *models.Category) int {
	err := db.DB.Model(&models.Category{}).Where("id = ?", id).Updates(&category).Error
	if err != nil {
		return errormsg.ERROR
	}
	return errormsg.SUCCESS
}

// DeleteCategory 删除已有分类
func DeleteCategory(id int) int {
	err := db.DB.Where("id = ?", id).Delete(&models.Category{}).Error
	if err != nil {
		return errormsg.ERROR
	}
	return errormsg.SUCCESS
}
